package com.tuanzi.loan.web.bean.family.largeamount;

import com.google.common.collect.Lists;
import com.starbaba.model.utils.JSONUtils;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.family.LoanLargeOuterTemplate;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.family.LoanLargeOuterTemplateService;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.vo.view.family.LargeAmountTempDownInfo;
import com.tuanzi.loan.vo.view.family.LargeAmountTempSubTagInfo;
import com.tuanzi.loan.vo.view.family.LargeAmountTempTagInfo;
import com.tuanzi.loan.web.bean.CurrentUserBean;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * User: liangZongXi
 * Create time: 16:12 2019/6/4
 * Description:
 */
@Data
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class LoanLargeOuterTemplateInfoBean extends JSFInfoBean<LoanLargeOuterTemplate> {

    private static final long serialVersionUID = -7455451707493422201L;

    @Autowired
    private CurrentUserBean currentUserBean;
    @Autowired
    private LoanLargeOuterTemplateService loanLargeOuterTemplateService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private DictionaryService dictionaryService;

    private List<LargeAmountTempDownInfo> androidDownList = new ArrayList<>();
    private List<LargeAmountTempDownInfo> iosDownList = new ArrayList<>();
    private String androidAmountTag;
    private String iosAmountTag;


    @PostConstruct
    public void init() {
        String idStr = getParamFromRequest("id");
        long id = NumberUtils.toLong(idStr);
        if(0 != id){ //编辑
           $ = loanLargeOuterTemplateService.findOne(id);
            if(Objects.isNull($)){
                forceRedirect(currentUserBean.getBack());
            }

        }else{ //新增
            $ = new LoanLargeOuterTemplate();
            changeStatusToEdit();
        }

        initDownInfo($);
        initAmountTag($);
    }

    private void initAmountTag(LoanLargeOuterTemplate loanLargeOuterTemplate){
        String androidAmountTag = loanLargeOuterTemplate.getAndroidAmountTag();
        if(StringUtils.isNoneBlank(androidAmountTag)){
            this.androidAmountTag = JSONUtils.checkAsString(JSONUtils.toJsonObject(androidAmountTag), "tagName");
        }

        String iosAmountTag = loanLargeOuterTemplate.getIosAmountTag();
        if(StringUtils.isNoneBlank(iosAmountTag)){
            this.iosAmountTag = JSONUtils.checkAsString(JSONUtils.toJsonObject(iosAmountTag), "tagName");
        }
    }

    private void initDownInfo(LoanLargeOuterTemplate loanLargeOuterTemplate){
        String androidDownLoadInfo = loanLargeOuterTemplate.getAndroidDownLoadInfo();
        if(StringUtils.isNotBlank(androidDownLoadInfo)){
            androidDownList = JSONUtils.fromJsonArrayNew(androidDownLoadInfo, LargeAmountTempDownInfo.class);
        }

        String iosDownLoadInfo = loanLargeOuterTemplate.getIosDownLoadInfo();
        if(StringUtils.isNotBlank(iosDownLoadInfo)){
            iosDownList = JSONUtils.fromJsonArrayNew(iosDownLoadInfo, LargeAmountTempDownInfo.class);
        }

        //补充到3个
        int size = androidDownList.size();
        for (int i=0; i< 3- size; i++){
            androidDownList.add(new LargeAmountTempDownInfo());
        }

        int iosSize = iosDownList.size();
        for (int i=0; i< 3- iosSize; i++){
            iosDownList.add(new LargeAmountTempDownInfo());
        }
    }

    public void onSave(){
        Integer templateId = $.getTemplateId();
        if(templateId == null){
            addErrorMessage("模板id不能为空");
            return;
        }

        if(null == $.getId()){
            LoanLargeOuterTemplate templateInfo = loanLargeOuterTemplateService.findLoanLargeOuterTemplateByTemplateId(templateId);
            if(null != templateInfo){
                addErrorMessage("模板ID已经存在，请重新配置");
                return;
            }
        }

        List<LargeAmountTempDownInfo> aDownInfoList = androidDownList.stream()
                .filter(info -> info.getChannelCode() != null && info.getProductId() != null).collect(Collectors.toList());
        if(aDownInfoList.size() > 0 && $.getAndroidRegType() == 2){
            $.setAndroidDownLoadInfo(JSONUtils.toJsonString(aDownInfoList));
        }else{
            $.setAndroidDownLoadInfo(null);
        }

        List<LargeAmountTempDownInfo> iDownInfoList = iosDownList.stream()
                .filter(info -> info.getChannelCode() != null && info.getProductId() != null).collect(Collectors.toList());
        if(iDownInfoList.size() > 0 && $.getIosRegType() == 2){
            $.setIosDownLoadInfo(JSONUtils.toJsonString(iDownInfoList));
        }else {
            $.setIosDownLoadInfo(null);
        }

        List<String> codes = Lists.newArrayList(androidAmountTag, iosAmountTag);
        Map<String, List<Dictionary>> tagListMap = dictionaryService.batchFindByCodes(codes);
        //安卓金额标签信息
        LargeAmountTempTagInfo androidTagInfo = getAmountTagInfo(androidAmountTag, tagListMap);
        $.setAndroidAmountTag(JSONUtils.toJsonString(androidTagInfo));
        //ios金额标签信息
        LargeAmountTempTagInfo iosTagInfo = getAmountTagInfo(iosAmountTag, tagListMap);
        $.setIosAmountTag(JSONUtils.toJsonString(iosTagInfo));

        //城市选择框信息
        Integer androidCityType = $.getAndroidCityType();
        Integer iosCityType = $.getIosCityType();
        String cityInfo = dictionaryService.findValueByCodeAndName(DictionaryCode.LARGE_OUTER_CITY_INFO, "city-info");
        $.setAndroidCityInfo(2 == androidCityType ? cityInfo : null);
        $.setIosCityInfo(2 == iosCityType ? cityInfo : null);

        this.$ = loanLargeOuterTemplateService.saveOrUpdate($);
        stringRedisTemplate.delete(LoanRedisKey.LOAN_LARGE_OUTER_TEMPLATE + $.getTemplateId());
        changeStatusToView();
        addSuccessfullyMessage();
    }

    private LargeAmountTempTagInfo getAmountTagInfo(String dicName, Map<String, List<Dictionary>> tagListMap){
        LargeAmountTempTagInfo infoTag = new LargeAmountTempTagInfo();
        List<LargeAmountTempSubTagInfo> subTagInfoList = Lists.newArrayList();
        infoTag.setTagName(dicName);
        for (Dictionary dic : tagListMap.get(dicName)) {
            LargeAmountTempSubTagInfo tagInfo = new LargeAmountTempSubTagInfo();
            tagInfo.setTagName(dic.getName());
            tagInfo.setTagValue(dic.getValue1());
            tagInfo.setCityShow(dic.getValue2() == null ? null : Integer.parseInt(dic.getValue2()));
            subTagInfoList.add(tagInfo);
        }
        infoTag.setTagInfoList(subTagInfoList);

        return infoTag;
    }



    public void onUploadAndroidBanner(FileUploadEvent event) {
        $.setAndroidBannerImageUrl(this.uploadImg(event.getFile()));
    }

    public void onUploadAndroidRemarkImg(FileUploadEvent event) {
        $.setAndroidRemarkImageUrl(this.uploadImg(event.getFile()));
    }

    public void onUploadIosBanner(FileUploadEvent event) {
        $.setIosBannerImageUrl(this.uploadImg(event.getFile()));
    }

    public void onUploadIosRemarkImg(FileUploadEvent event) {
        $.setIosRemarkImageUrl(this.uploadImg(event.getFile()));
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(DictionaryCode.EXTRA_TEMPLATE_PC_SHOW, DictionaryCode.LOAN_LARGE_OUTER_TEMPLATE_COLOR,
                DictionaryCode.LOAN_LARGE_OUTER_TEMPLATE_REG_TYPE, DictionaryCode.LARGE_OUTER_TAG_LIST,
                DictionaryCode.LARGE_OUTER_CITY_TYPE);
    }
}
